package com.ruoyi.framework.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录用户的工具类
 * @author dry
 * @since 2022-04-17 19:40:20
 */
public class LoginUserUtils {

    /**
     * 登录用户的id
     */
    public static final String LOGIN_USER_ID="loginUserId";
    /**
     * 登录用户的name
     */
    public static final String LOGIN_USER_NAME="loginUserName";


    /**
     * 获取当前用户的id
     * @return
     */
    public static Long getLoginUserId(){
        Object userId = getRequest().getAttribute(LOGIN_USER_ID);
        if (userId == null){
            return null;
        }
        if (userId instanceof Long){
            return (long)userId;
        }
        return Long.valueOf(userId.toString());

    }


    /**
     * 获取当前用户的id
     * @return
     */
    public static String getStrLoginUserId(){
        Object userId = getRequest().getAttribute(LOGIN_USER_ID);
        if (userId == null){
            return null;
        }

        return userId.toString();

    }

    /**
     * 获取当前登录用户的名字
     * @return
     */
    public static String getLoginUserName(){
        Object userName = getRequest().getAttribute(LOGIN_USER_NAME);
        if (userName == null){
            return null;
        }
        return userName.toString();
    }

    /**
     * 获得request
     * @return
     */
    private static HttpServletRequest getRequest() {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getRequest();

    }





}
